/**
 * @author johon
 * @namespace phonegap接口封装类
 */
var phoneGap = {
	/**
     * 数据来源参数的一个常量
     * 初始化后，可以如下调用来设置获取图片的方式
     * 1、从本地相册获取图片phoneGap.pictureSource.SAVEDPHOTOALBUM
     * 2、拍照后获取图片phoneGap.pictureSource.CAMERA
     * @type String
     */
	pictureSource:"",
	/**
     * 设置getPicture的结果类型
     * @type String
     */
	destinationType:"", 
	/**
     * 获取的图片路径（未用到）
     * @type String
     */
	pickUrl:"",
	/**
     * 内存卡中的项目主文件夹
     * @type String
     */
	appRootFilePath:'LeXin',
	/**
     * 项目文件夹，缓存图片
     * @type String
     */
	appImgPath:'LeXin/img',
	/**
     * 项目文件夹，缓存头像
     * @type String
     */
	photoPath:'LeXin/img/head',
	/**
     * 项目文件夹，缓存文件(未用到)
     * @type String
     */
	appCachePath:'LeXin/cache',
	/**
	 * 初始化
	 */
	init:function(){	
		this.pictureSource = navigator.camera.PictureSourceType;  
        this.destinationType = navigator.camera.DestinationType;
        console.log("phonegap init...");
	},
	/**
     * 从本地获取用户头象
     * @param  String source          获取图片的方法
     * @param  String showImgId       显示头像的img元素id
     * @param  Function(imageUrl,showImgId)  successCallback 获取图片后的回调,会传出图片的本地路径imageUrl,和图片的img显示id
     * @example
     * 使用方法：
     * 1、拍照获取头像
     * phoneGap.takeUserphotoFrom(phoneGap.pictureSource.CAMERA,'currUserphoto',setting.updatePhoto);
     * 2、从本地相册获取头像
     * phoneGap.takeUserphotoFrom(phoneGap.pictureSource.SAVEDPHOTOALBUM,'currUserphoto',setting.updatePhoto);
     */
	takeUserphotoFrom:function(source,showImgId,successCallback){
		this.takePicFrom(source,showImgId,true,246,246,successCallback);
	},
	/**
     * 从手机中读取图片，或拍照获得图片
     * @param  String  source         获取图片的方式
     * @param  String  showImgId      显示图片的img元素id
     * @param  Boolean isEdit         获取图片后是否可编辑，即是否可裁剪
     * @param  Number  width          输出图片的宽度
     * @param  Number  height         输出图片的高度
     * @param  Function(imageUrl,showImgId)  successCallback 获取图片后的回调,会传出图片的本地路径imageUrl,和图片的img显示id
     */
	takePicFrom:function(source,showImgId,isEdit,width,height,successCallback){
		
		var that = this;
		navigator.camera.getPicture(function(imageURI){ 
                var image = $("#"+showImgId); 
                //image.style.display = 'block';  
//                image.attr("src",imageURI);
//                that.pickUrl = imageURI;  
				if(successCallback!=null){
					successCallback.call(this,imageURI,showImgId);
					
				}
            }, function(msg){ 
                if(source==that.pictureSource.CAMERA)  
                    console.log('加载照相机出错!');  
                else  
                    console.log('加载相册出错!');  
            }, {  
                quality : 50,   
                destinationType : that.destinationType.FILE_URI,  
                sourceType : source,
/*				saveToPhotoAlbum: true,*/
				allowEdit: (typeof(isEdit)=="boolean"?isEdit:false),
				targetHeight:(typeof(height)=="number"?width:-1),
				targetWidth:(typeof(width)=="number"?width:-1)
        });  
	},
	/**
     * 上传本地文件
     * @param  String panelId        当前页面的id
     * @param  String localfileUrl    图片的本地路径
     * @param  String uploadUri       上传至服务器的url地址
     * @param  String key             定义上传至服务器的变量，服务器通过解析改变量获取文件
     * @param  String mimeType        上传的文件类型，格式如"image/jpeg"
     * @param  Function(imageUrl) successCallback 上传成功后的回调,传出图片本地路径
     * @param  Function failCallback    上传失败后的回调
     * @example
     * 使用方法：见phoneGap.uploadImage()方法
     * 
     */
	uploadFile:function(panelId,localfileUrl,uploadUri,key,mimeType,successCallback,failCallback) {     
        if(typeof(localfileUrl)!="string")  
            app.message('请先选择本地图片');  
        var options = new FileUploadOptions();  
        options.fileKey = typeof(key)=="string"?key:"photo";  
        options.fileName = localfileUrl.substr(localfileUrl.lastIndexOf('/') + 1);
        options.mimeType = mimeType;/*"image/jpeg"*/ 
        options.params = {fileType:"jpeg"};
        var ft = new FileTransfer();  
        app.message("更新中...","blue","white",panelId,0);
        ft.upload(  
        	localfileUrl,  
	        encodeURI(app.host+uploadUri),  
	        function(data){ 
        		app.hideMessage(panelId,true);
        		var response = JSON.parse(data.response);
        		if(response.result=="true"){
        			app.message("更新成功！");
        			successCallback && successCallback.call(this,response.imgUrl);
        		}else{
        			app.message("更新失败！")
        			failCallback && failCallback.call(this);
        		}
        	},   
	        function(error){ 
        		app.hideMessage(panelId,true);
        		app.message("上传失败，请重试！");
        	},  
	        options);
    },
    /**
     * 上传图片
     * @param  String panelId       当前页面id
     * @param  String localfileUrl   本地图片路径
     * @param  String uploadUri      上传至服务器的url地址
     * @param  String filekey        变量
     * @param  Function(imageUrl) successCallback 成功后回调
     * @param  Function failCallback    失败后回调
     *
     * @example
     * 使用方法：
     * phoneGap.uploadImage("account_subpage",imageURI,"/lexin/updatePhoto.do","photo",function(imgUrl){
            var $cuuUserPhoto1 = $.query("#account_subpage").find("#currUserphoto");
            var $cuuUserPhoto2 = $.query("#user_switch_subpage").find("#currUserphoto");
            $cuuUserPhoto1.attr("src",imageURI);
            $cuuUserPhoto2.attr("src",imageURI);
            app.currUser.photo_src=imgUrl;
            db.updateDatas("local_users", ["photo_src"], ["imgUrl"], "id='"+app.currUser.id+"'", function(){
                $cuuUserPhoto1.attr("src",app.host+imgUrl);
                $cuuUserPhoto2.attr("src",app.host+imgUrl);
            })
        });
     */
    uploadImage:function(panelId,localfileUrl,uploadUri,filekey,successCallback,failCallback){
    	var type = localfileUrl.substr(localfileUrl.lastIndexOf('.') + 1);
    	phoneGap.uploadFile(panelId,localfileUrl,uploadUri,filekey,"image/jpeg",successCallback,failCallback);
    },
    /**
     * 下载文件（未优化）
     * @param  {[type]} sourceUrl [description]
     * @param  {[type]} targetUrl [description]
     * @return {[type]}           [description]
     */
    downloadFile:function(sourceUrl,targetUrl){  
        var fileTransfer = new FileTransfer();   
        var uri = encodeURI(sourceUrl);    
  
        fileTransfer.download(  
        uri,targetUrl,function(entry){   
        	hideProgressBar(fileTransfer);
            var smallImage = document.getElementById('bg');  
            smallImage.style.display = 'block';   
            smallImage.src = entry.fullPath;   
        },function(error){  
            console.log("下载网络图片出现错误");  
        });  
    },
    /**
     * 下载或上传的进度显示方法（未优化）
     * @param  {[type]} fileTransfer [description]
     * @return {[type]}              [description]
     */
    onProgress:function(fileTransfer){
        fileTransfer.onprogress = function(progressEvent){
        	if (progressEvent.lengthComputable) {  
                //已经上传  
                var loaded=progressEvent.loaded;  
                //<strong><strong>文件</strong></strong>总长度  
                var total=progressEvent.total*2;
                //计算百分比，用于显示<strong>进度</strong>条  
                var percent=parseInt((loaded/total)*100);  
                //换算成MB  
                loaded=(loaded/1024/1024).toFixed(2);  
                total=(total/1024/1024).toFixed(2);  
                //$('#process_info').html(loaded+'M/'+total+'M');  
                $('.upload_current_process').css({'width':percent+'%'}); 
            }  
        };
        $('.upload_process_bar').show();
    },
    /**
     * 读取本地文件，不存在则下载(未优化)
     * @param  {[type]} uri          [description]
     * @param  {[type]} targetUrl    [description]
     * @param  {[type]} doneCallback [description]
     * @return {[type]}              [description]
     */
    getlocalFile:function(uri,targetUrl,doneCallback){ 
    	var that = this; 
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){   
            //创建目录  
             fileSystem.root.getDirectory(PhoneGapUtil.photoPath, {create:true},   
                function(fileEntry){},   
                function(msg){console.log("创建目录失败"+msg);});  
  
             var _localFile = targetUrl;  
             var _url = uri;  
             //查找文件  
             fileSystem.root.getFile(_localFile, null, function(fileEntry){  
                //文件存在就直接显示  
                var src = fileEntry.fullPath;
				doneCallback.call(this,src);
            }, function(){    
                //否则就到网络下载图片!  
                fileSystem.root.getFile(_localFile, {create:true}, function(fileEntry){  
                    var targetURL = fileEntry.toURL();  
                    downloadPic(_url,targetURL);   
                 },function(){  
                    alert('下载图片出错');  
                 });   
            });  
      
        }, function(evt){  
            console.log("加载文件系统出现错误");  
        });   
    },
    /**
     * 获取当前网络的类型
     * @return String 当前网络连接类型2g,3g,wifi等等，若未连接网络，则为none
     */
    currNetWork:function(){
    	return navigator.network.connection.type
    }
};